import React, { PureComponent as Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Form, Button, Input, Icon, message } from 'antd';
import { withRouter } from 'react-router';
import * as XLSX from 'xlsx';
const FormItem = Form.Item;
const formItemStyle = {
  marginBottom: '.16rem'
};
const changeHeight = {
  height: '.42rem'
};

@connect(
  state => {
    return {
      loginData: state.user
    };
  }
)
@withRouter
class Reg extends Component {
  constructor(props) {
    super(props);
    this.state = {
      confirmDirty: false
    };
  }

  static propTypes = {
    form: PropTypes.object,
    history: PropTypes.object,
    onSubmit: PropTypes.func,
    onCancel: PropTypes.func,
    onSubmits: PropTypes.func
  };

  handleSubmit = e => {
    e.preventDefault();
    const form = this.props.form;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.props.onSubmit(values);
      }
    });
  };

  onImportExcel = file => {
    // 获取上传的文件对象
    const { files } = file.target;
    // 通过FileReader对象读取文件
    const fileReader = new FileReader();
    fileReader.onload = event => {
      try {
        const { result } = event.target;
        // 以二进制流方式读取得到整份excel表格对象
        const workbook = XLSX.read(result, { type: 'binary' });
         // 存储获取到的数据
        let data = [];
        // 遍历每张工作表进行读取（这里默认只读取第一张表）
        for (const sheet in workbook.Sheets) {
          // esline-disable-next-line
          if (workbook.Sheets.hasOwnProperty(sheet)) {
            // 利用 sheet_to_json 方法将 excel 转成 json 数据
            data = data.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
            break; // 如果只取第一张表，就取消注释这行
          }
        }

        this.props.onSubmits(data);

      } catch (e) {
        // 这里可以抛出文件类型错误不正确的相关提示
        message.error('文件类型不正确！');
      }
    };
    // 以二进制方式打开文件
    fileReader.readAsBinaryString(files[0]);
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    return (
      <div>
        <Form onSubmit={this.handleSubmit}>
          {/* 用户名 */}
          <FormItem style={formItemStyle}>
            {getFieldDecorator('userName', {
              rules: [{ required: true, message: '请输入用户名!' }]
            })(
              <Input
                style={changeHeight}
                prefix={<Icon type="user" style={{ fontSize: 13 }} />}
                placeholder="Username"
              />
            )}
          </FormItem>

          {/* Emaiil */}
          <FormItem style={formItemStyle}>
            {getFieldDecorator('email', {
              rules: [
                {
                  required: true,
                  message: '请输入email!',
                  pattern: /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{1,})+$/
                }
              ]
            })(
              <Input
                style={changeHeight}
                prefix={<Icon type="mail" style={{ fontSize: 13 }} />}
                placeholder="Email"
              />
            )}
          </FormItem>

          {/* 中文名称 */}
          <FormItem style={formItemStyle}>
            {getFieldDecorator('cname', {
              rules: [{ required: true, message: '请输入中文名称!' }]
            })(
              <Input
                style={changeHeight}
                prefix={<Icon type="user" style={{ fontSize: 13 }} />}
                placeholder="中文名称"
              />
            )}
          </FormItem>

          {/* cellphone */}
          <FormItem style={formItemStyle}>
            {getFieldDecorator('cellphone', {
              // rules: [{ required: true, message: '请输入Phone!' }]
            })(
              <Input
                style={changeHeight}
                prefix={<Icon type="phone" style={{ fontSize: 13 }} />}
                placeholder="Phone(可不填)"
              />
            )}
          </FormItem>

          {/* RTX编号 */}
          <FormItem style={formItemStyle}>
            {getFieldDecorator('rtxno', {
              rules: [{ required: true, message: '请输入RTX编号!' }]
            })(
              <Input
                style={changeHeight}
                prefix={<Icon type="phone" style={{ fontSize: 13 }} />}
                placeholder="RTX编号"
              />
            )}
          </FormItem>
          
          {/* 批量添加 */}
          <FormItem style={formItemStyle}>
            <input
              type='file'
              accept='.xlsx, .xls'
              onChange={this.onImportExcel}
            />
            <p>支持 .xlsx、.xls 格式的文件</p>
          </FormItem>

          {/* 添加按钮 */}
          <FormItem style={formItemStyle}>
            <Button type="primary" htmlType="submit" style={{marginRight: '15px'}}>
              添加
            </Button>
            <Button type="primary" onClick={this.props.onCancel}>
              取消
            </Button>
          </FormItem>

        </Form>
      </div>
    );
  }
}
const RegForm = Form.create()(Reg);
export default RegForm;
